package com.lanhai.system;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lanhai.Main;
import com.lanhai.model.Agv;
import com.lanhai.model.ControlArea;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;







public class SearchHandler implements HttpHandler {
	private static final Logger logger = Logger.getLogger(SearchHandler.class);
	
	public Main main;
	
    @Override
    public void handle(HttpExchange httpExchange) {    		
        InputStream is = httpExchange.getRequestBody();
        String requestData = "";
        try{
        	requestData = is2string(is);
        }catch(Exception e){
        	e.printStackTrace();
        }
        //System.out.println(requestData); 
        //String queryParams = httpExchange.getRequestURI().getQuery();
        //System.out.println(queryParams);
        String response = "";
        
        Map<String, Object> resultMap = new HashMap<String, Object>();
        JSONObject requestParam = JSONObject.parseObject(new String(requestData));
        String requestType = requestParam.getString("type");
        
        if(requestType.equals("log")){
        	logger.info(requestType);
//        	DBHelper conn1 = new DBHelper();
//        	DBHelper conn2 = new DBHelper();
//    		String sql = "select * from input_log";
//    		String oSql = "select * from output_log";
//    		String clientNo = requestParam.getString("clientNo");
//    		String clientType = requestParam.getString("clientType");
//    		String beginTime = requestParam.getString("beginTime");
//    		String endTime = requestParam.getString("endTime");
//    		if(clientType.equals("AGV")){
//    			sql += " where clientType='AGV' and clientNo='" + clientNo + "'";
//    			oSql += " where clientType='AGV' and clientNo='" + clientNo + "'";
//    		}else if(clientType.equals("Park")){
//    			sql += " where clientType='Park' and clientNo='" + clientNo + "'";
//    			oSql += " where clientType='Park' and clientNo='" + clientNo + "'";
//    		}
//    		if(beginTime != null && endTime != null){
//    			sql += " and inputTime>'" + beginTime + "'";
//    			sql += " and inputTime<'" + endTime + "'";
//    			oSql += " and outputTime>'" + beginTime + "'";
//    			oSql += " and outputTime<'" + endTime + "'";
//    		}
//			sql += " order by id desc limit 200";
//			oSql += " order by id desc limit 200";
//			System.out.println(sql);
//			try{
//				ResultSet iResultSet = conn1.executeQuery(sql, main.dataSource);
//				ResultSet oResultSet = conn2.executeQuery(oSql, main.dataSource);
//				if(iResultSet != null){
//	    			JSONArray inputLog = convertJson(iResultSet);
//	    			resultMap.put("inputLog", inputLog);    				
//				}
//				if(oResultSet != null){
//	    			JSONArray outputLog = convertJson(oResultSet);
//	    			resultMap.put("outputLog", outputLog);    				
//				}				
//			}catch(Exception e){
//				e.printStackTrace();
//			}finally{
//				conn1.close();
//				conn2.close();
//			}
			resultMap.put("success", true);
        }else if(requestType.equals("job")){
//        	DBHelper conn = new DBHelper();
//    		String beginTime = requestParam.getString("beginTime");
//    		String endTime = requestParam.getString("endTime");
//    		String agvId = requestParam.getString("agvId");
//    		String line = requestParam.getString("line");
//    		String sql = "select * from job where 1=1";
//    		if(!(beginTime.equals("") && endTime.equals(""))){
//    			sql += " and callTime>'" + beginTime + "' and callTime<'" + endTime + "'";
//    		}
//    		if(!agvId.equals("")){
//    			sql += " and agvId=" + agvId;
//    		}
//    		if(!line.equals("")){
//    			sql += " and mwLine='" + line + "'";
//    		}
//    		sql += " order by finishTime desc";
//    		try{
//        		ResultSet ResultSet = conn.executeQuery(sql, main.dataSource);
//    			if(ResultSet != null){
//        			JSONArray resultList = convertJson(ResultSet);
//        			resultMap.put("data", resultList);    				
//    			}
//    			resultMap.put("success", true);      			
//    		}catch(Exception e){
//    			e.printStackTrace();
//    		}finally{
//    			conn.close();
//    		}
        }else if(requestType.equals("agv")){
        	JSONArray resultList = new JSONArray();
        	for(Map.Entry<Integer, Agv> m:main.agvMap.entrySet()){
        		Agv a = m.getValue();
        		String agvStr = JSON.toJSONString(a);
            	JSONObject aj = JSONObject.parseObject(agvStr);
        		resultList.add(aj);
        		resultMap.put("data", resultList);
        	}
        	resultMap.put("success", true); 
        }else if(requestType.equals("ca")){
        	JSONArray resultList = new JSONArray();
        	for(Map.Entry<Integer, ControlArea> m:main.controlAreaMap.entrySet()){
        		ControlArea ca = m.getValue();
        		String caStr = JSON.toJSONString(ca);
            	JSONObject obj = JSONObject.parseObject(caStr);
        		resultList.add(obj);
        		resultMap.put("data", resultList);
        	}
        	resultMap.put("success", true); 
        }else{
        	resultMap.put("success", false);
        }
        try{
            response = JSON.toJSONString(resultMap);
            //System.out.println("response: " + response);        
            is.close();
            
            Headers responseHeaders = httpExchange.getResponseHeaders();
            responseHeaders.set("Content-Type", "text/json;charset=utf-8");
            responseHeaders.set("Access-Control-Allow-Origin", "*");
            responseHeaders.set("Cache-Control","no-cache");
            httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.getBytes().length); 
            OutputStream os = httpExchange.getResponseBody();
            os.write(response.getBytes());
            os.flush();
            os.close();          	
        }catch(Exception e){
        	e.printStackTrace();
        }
    }
	
    public void init(Main main){
    	this.main = main;
    }
    
    private String is2string(InputStream is) throws IOException {
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(is, "UTF-8");
        
        for (; ; ) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
        return out.toString();
    }
    
    public JSONArray convertJson(ResultSet resultSet) throws Exception{
    	JSONArray list = new JSONArray();
    	//获取结果集的列数
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
    	while (resultSet.next()) {
            JSONObject jsonObj = new JSONObject();
            // 遍历每一列
            for (int i = 1; i <= columnCount; i++) {
                String columnName =metaData.getColumnLabel(i);
                String value = resultSet.getString(columnName);
                jsonObj.put(columnName, value);
            }   
            list.add(jsonObj);
    	}
    	return list;
    }
    
}
